package com.xsomnus.network_programming.netty.tcp;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author 叶小夏
 * @since 2019-08-21 16:22
 *
 * VM Args: -Dio.netty.leakDetectionLevel=ADVANCED
 */
public class EchoServer {

    public static final int port = 9091;

    public static void main(String[] args) {

        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(4);
        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.group(boosGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new EchoServerHandler());
                            ch.pipeline().addLast(new EchoServerHandlerV2());
                        }
                    });
            ChannelFuture future = sb.bind(port).sync();
            if (future.isSuccess()) {
                System.out.println("start server on port " + port + "success");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
